package com.ens.app;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class EncryptionDetailActivity extends Activity {

	final int ACTIVITY_CHOOSE_FILE = 1;
	byte[] encSalt;
	Bundle extras;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.encryption_activity);
        extras = getIntent().getExtras();
		android.view.View encryptionPasswordField = findViewById(R.id.pwEncryptionPw);

		// http://twigstechtips.blogspot.com/2011/08/android-how-to-select-file.html
		android.view.View buttonChooseSalt = findViewById(R.id.buttonChooseSalt);
		buttonChooseSalt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(android.view.View v) {
				Intent chooseFile;
				Intent intent;
				chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
				chooseFile.setType("file/*");
				intent = Intent.createChooser(chooseFile, "Choose your salt");
				startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
			}
		});

		android.view.View chooseAPluginButton = findViewById(R.id.buttonChooseAPlugin);
		chooseAPluginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(android.view.View v) {
				Intent i = new Intent(EncryptionDetailActivity.this,
						PluginChooserActivity.class);
				extras.putString("userEncryptionPw", ((EditText) findViewById(R.id.pwEncryptionPw)).getText().toString());
	            i.putExtras(extras);
				startActivity(i);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case ACTIVITY_CHOOSE_FILE: {
			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
				String filePath = uri.getPath();
				java.io.File saltFile = new java.io.File(filePath);
				if (saltFile.exists()) {
					java.io.ObjectInputStream is;
					try {
						is = new java.io.ObjectInputStream(
								new java.io.FileInputStream(saltFile));
						byte[] tmp = encSalt = (byte[]) is.readObject();
						extras.putByteArray("userSalt", tmp);
						is.close();
						// http://stackoverflow.com/questions/4590957/how-to-set-text-in-an-edittext
						EditText saltField = (EditText) findViewById(R.id.editSalt);
						saltField.setText(new String(tmp));
					} catch (java.io.FileNotFoundException e) {
						e.printStackTrace();
					} catch (java.io.IOException e) {
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				}
			}
		}
		}
	}
}
